package com.shj.em.aa.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.shj.em.common.to.Tree;
import com.shj.em.aa.entity.Resource;
import com.shj.em.aa.mapper.ResourceMapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.shj.em.biz.Constants;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 资源 服务实现类
 * </p>
 *
 * @author Shen Huang Jian
 * @since 2018-06-21
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    public List<Resource> findResByUserLoginId(String userId){
        return resourceMapper.findResByUserLoginId(userId);
    }

    public List<Resource> findResByUserId(Long userId){
        return resourceMapper.findResByUserId(userId);
    }

    public List<Resource> findResByRoleId(Long roleId){
        return resourceMapper.findAssignedResToRole(roleId);
    }

    public List<Resource> findAllRes(){
        Wrapper<Resource> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag", 0);
        return resourceMapper.selectList(wrapper);
    }

    @Override
    public List<Tree<Resource>> getMenus(String uid) {
        List<Tree<Resource>> trees = new ArrayList<Tree<Resource>>();

        boolean isSuper = SecurityUtils.getSubject().hasRole(Constants.ROLE_SUPER);

        //如果是管理员，则列出所有菜单
        String userId = isSuper ? null : uid;
        Map<String, String> params = new HashMap<>();
        params.put("uid", userId);

        List<Resource> reslist = resourceMapper.getMenuResourcesByUserId(params);
        for (Resource res : reslist) {
            Tree<Resource> tree = new Tree<Resource>();
            tree.setId(res.getId().toString());
            tree.setParentId(res.getParentId().toString());
            tree.setName(res.getName());
            tree.setPath(res.getUrl());
            tree.setIcon(res.getIcon());
            trees.add(tree);
        }
        // 默认顶级菜单为-1，根据数据库实际情况调整
        List<Tree<Resource>> list = Tree.buildTree(trees, "-1");

        List<Tree<Resource>> returnList = new ArrayList<Tree<Resource>>();
        //清除空的父菜单
        for(Tree<Resource> item : list){
            if(!item.getChild().isEmpty()){
                returnList.add(item);
            }
        }

        return returnList;
    }

}
